package com.example.qu_tao.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import com.example.qu_tao.R;
import com.example.qu_tao.View.ZuJiActivity;
import com.example.qu_tao.database.DBHelper;
import java.util.List;
import java.util.Map;

public class FootprintAdapter extends BaseAdapter {

    private Context context;
    private List<Map<String, Object>> dataList;
    private DBHelper dbHelper;

    public FootprintAdapter(Context context, List<Map<String, Object>> dataList) {
        this.context = context;
        this.dataList = dataList;
        this.dbHelper = new DBHelper(context);
    }

    @Override
    public int getCount() {
        return dataList.size();
    }

    @Override
    public Object getItem(int position) {
        return dataList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.item_history, parent, false);
            holder = new ViewHolder();
            holder.textViewName = convertView.findViewById(R.id.text_view_name);
            holder.textViewPrice = convertView.findViewById(R.id.text_view_price);
            holder.btnDelete = convertView.findViewById(R.id.btn_delete);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        Map<String, Object> item = dataList.get(position);
        holder.textViewName.setText(item.get("goods_name").toString());
        holder.textViewPrice.setText("¥" + item.get("goods_price").toString());

        // 设置删除按钮点击事件
        holder.btnDelete.setOnClickListener(v -> {
            int goodsId = (int) item.get("goods_id");
            // 从数据库中删除记录
            dbHelper.getWritableDatabase().delete(DBHelper.TABLE_NAME_FOOTPRINT, "goods_id = ?", new String[]{String.valueOf(goodsId)});
            // 从列表中移除该项
            dataList.remove(position);
            // 通知适配器数据已改变
            notifyDataSetChanged();
            // 检查列表是否为空
            if (dataList.isEmpty()) {
                ((ZuJiActivity) context).updateEmptyViewVisibility(true);
            }
        });

        return convertView;
    }

    private static class ViewHolder {
        TextView textViewName;
        TextView textViewPrice;
        Button btnDelete;
    }
}